package com.library.management.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.library.management.common.PageResult;
import com.library.management.common.BorrowRecordStats;
import com.library.management.entity.Book;
import com.library.management.entity.BorrowRecord;
import com.library.management.mapper.BookMapper;
import com.library.management.mapper.BorrowRecordMapper;
import com.library.management.service.BorrowRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 借阅记录服务实现类
 */
@Service
public class BorrowRecordServiceImpl implements BorrowRecordService {
    @Autowired
    private BorrowRecordMapper borrowRecordMapper;

    @Autowired
    private BookMapper bookMapper;

    @Override
    @Transactional
    public int borrow(BorrowRecord borrowRecord) {
        // 检查图书库存
        Book book = bookMapper.selectById(borrowRecord.getBookId());
        if (book == null || book.getStock() <= 0) {
            throw new RuntimeException("图书库存不足");
        }

        // 减少图书库存
        bookMapper.updateStock(borrowRecord.getBookId(), book.getStock() - 1);

        // 设置借阅时间为当前时间
        borrowRecord.setBorrowTime(LocalDateTime.now());

        // 设置借阅状态为借阅中
        borrowRecord.setStatus(1);

        // 添加借阅记录
        return borrowRecordMapper.insert(borrowRecord);
    }

    @Override
    @Transactional
    public int returnBook(Long id) {
        try {
            // 查询借阅记录
            BorrowRecord borrowRecord = borrowRecordMapper.selectById(id);
            if (borrowRecord == null) {
                throw new RuntimeException("借阅记录不存在");
            }

            // 检查是否已归还
            if (borrowRecord.getStatus() == 2) {
                throw new RuntimeException("图书已归还");
            }

            // 增加图书库存
            Book book = bookMapper.selectById(borrowRecord.getBookId());
            if (book == null) {
                throw new RuntimeException("图书不存在或已被删除");
            }
            bookMapper.updateStock(borrowRecord.getBookId(), book.getStock() + 1);

            // 更新借阅记录
            BorrowRecord record = new BorrowRecord();
            record.setId(id);
            record.setActualReturnTime(LocalDateTime.now());
            record.setStatus(2); // 已归还

            int updatedRows = borrowRecordMapper.update(record);
            System.out.println("Attempting to return book with ID: " + id + ", Updated rows: " + updatedRows);
            return updatedRows;
        } catch (Exception e) {
            System.err.println("Error returning book with ID: " + id);
            e.printStackTrace();
            throw new RuntimeException("归还图书失败: " + e.getMessage(), e);
        }
    }

    @Override
    @Transactional
    public int cancel(Long id) {
        // 查询借阅记录
        BorrowRecord borrowRecord = borrowRecordMapper.selectById(id);
        if (borrowRecord == null) {
            throw new RuntimeException("借阅记录不存在");
        }

        // 检查是否可以取消
        if (borrowRecord.getStatus() != 1) {
            throw new RuntimeException("只能取消借阅中的记录");
        }

        // 增加图书库存
        Book book = bookMapper.selectById(borrowRecord.getBookId());
        bookMapper.updateStock(borrowRecord.getBookId(), book.getStock() + 1);

        // 更新借阅记录
        BorrowRecord record = new BorrowRecord();
        record.setId(id);
        record.setStatus(0); // 已取消

        return borrowRecordMapper.update(record);
    }

    @Override
    public BorrowRecord getById(Long id) {
        return borrowRecordMapper.selectById(id);
    }

    @Override
    public PageResult<BorrowRecord> list(BorrowRecord borrowRecord, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<BorrowRecord> list = borrowRecordMapper.selectList(borrowRecord);
        PageInfo<BorrowRecord> pageInfo = new PageInfo<>(list);
        return new PageResult<>(pageInfo.getTotal(), pageInfo.getList());
    }

    @Override
    public List<BorrowRecord> listByUserId(Long userId) {
        return borrowRecordMapper.selectByUserId(userId);
    }

    @Override
    public List<BorrowRecord> listByBookId(Long bookId) {
        return borrowRecordMapper.selectByBookId(bookId);
    }

    @Override
    public BorrowRecordStats getBorrowStatsByUserId(Long userId) {
        BorrowRecordStats stats = new BorrowRecordStats();

        // 总借阅数
        BorrowRecord totalFilter = new BorrowRecord();
        totalFilter.setUserId(userId);
        stats.setTotalBorrowCount(borrowRecordMapper.selectCount(totalFilter));

        // 当前借阅数 (状态为1)
        BorrowRecord currentFilter = new BorrowRecord();
        currentFilter.setUserId(userId);
        currentFilter.setStatus(1);
        stats.setCurrentBorrowCount(borrowRecordMapper.selectCount(currentFilter));

        // 逾期数量 (状态为3)
        BorrowRecord overdueFilter = new BorrowRecord();
        overdueFilter.setUserId(userId);
        overdueFilter.setStatus(3);
        stats.setOverdueCount(borrowRecordMapper.selectCount(overdueFilter));

        return stats;
    }
}